package com.kitty.common.schedule.task;

import com.kitty.common.schedule.entity.SpringScheduledCron;
import com.kitty.common.utils.SpringUtils;
import com.kitty.common.core.SchedulerManager;
import com.kitty.game.activity.service.boos.handler.DaRiJinWuHandlr;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.time.StopWatch;
import org.nutz.dao.Cnd;
import org.nutz.dao.Dao;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Calendar;
import java.util.Date;
import java.util.List;

@Component
@Slf4j
public class DaRiJinWuTask implements ScheduledOfTask{
    @Autowired
    Dao dao;
    @Autowired
    DaRiJinWuHandlr daRiJinWuHandlr;
    @Override
    public void execute() {
        //开启大日金乌。
        StopWatch stopWatch = new StopWatch();
        stopWatch.start();
        SpringUtils.getBean(DaRiJinWuHandlr.class).startDaRiActivity();
        stopWatch.stop();
        log.info("大日金乌开始，用时{}毫秒", stopWatch.getTime());

        List<SpringScheduledCron> SpringScheduledCronList = dao.query(SpringScheduledCron.class, Cnd.where("cron_key", "=","com.kitty.common.schedule.task.DaRiJinWuTask"));
        if(SpringScheduledCronList.size()>0){
            SpringScheduledCron springScheduledCron = SpringScheduledCronList.get(0);
            String cron_end = springScheduledCron.getCron_end();
            String[] split = cron_end.split(":");
            Calendar calendarEnd = Calendar.getInstance();
            calendarEnd.setTime(new Date());
            calendarEnd.set(Calendar.HOUR_OF_DAY, Integer.parseInt(split[0]));
            calendarEnd.set(Calendar.MINUTE, Integer.parseInt(split[1]));

            Calendar now=Calendar.getInstance();
            long nowTime=now.getTimeInMillis();
            long endTime = calendarEnd.getTimeInMillis();
            long time = endTime-nowTime;
            //发送消息
            SchedulerManager.getInstance().schedule(new Runnable() {
                @Override
                public void run() {
                    daRiJinWuHandlr.endDaRiActivity();
                }
            }, time);
        }

    }
}
